package org.javaongems.client.vcl;

import java.util.ArrayList;

import com.google.gwt.user.client.Timer;

public class ControlInvalidation {
	private ControlInvalidation() {}
	
	static protected ArrayList controlsToRepaint = new ArrayList();
	static protected boolean timerIsActive = false;

	static public void add(Control ctrl) {
		controlsToRepaint.add(ctrl);
		setDeferredRepaintTimerIfRequired();
	}

	static protected void repaintControls() {
		ArrayList repeatList = new ArrayList();
		for (int i = 0, max = controlsToRepaint.size(); i < max; ++i) {
			Control current = (Control) controlsToRepaint.remove(0);
			if (current == null) {
				return;
			} else {
				if (!repeatList.contains(current)) {
					repeatList.add(current);
					current.repaint();
				}
			}
		}
	}

	static protected void setDeferredRepaintTimerIfRequired() {
		if (!timerIsActive && !controlsToRepaint.isEmpty()) {
			new Timer() {
				public void run() {
					try {
						repaintControls();
					} finally {
						timerIsActive = false;
						setDeferredRepaintTimerIfRequired();
					}
				}
			}.schedule(1);
			timerIsActive = true;
		}
	}
}
